//
//  DataModel.swift
//  Checklists
//
//  Created by JokerAtBaoFeng on 16/3/10.
//  Copyright © 2016年 baofeng. All rights reserved.
//

import Foundation

class DataModel {
    var lists = [Checklist]()
    var indexOfSelectedChecklist: Int {
        get {
            return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex")
        }
        
        set {
            NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex")
        }
    }
    
    init(){
        loadChecklists()
        registerDefault()
        handleFristTime()
    }
    
    func documentsDirectory() ->String {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    func dataFilePath() -> String {
        let path: NSString = documentsDirectory() as NSString
        return path.stringByAppendingPathComponent("Checklists")
    }
    func loadChecklists(){
        let path = dataFilePath()
        if NSFileManager.defaultManager().fileExistsAtPath(path) {
            if let data = NSData(contentsOfFile: path) {
                let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
                lists = unarchiver.decodeObjectForKey("Checklists") as! [Checklist]
                unarchiver.finishDecoding()
            }
        }
        sortChecklists()
    }
    func saveChecklists(){
        let path = dataFilePath()
        
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(lists, forKey: "Checklists")
        archiver.finishEncoding()
        
        data.writeToFile(path, atomically: true)
    }
    func registerDefault(){
        let dictionary = ["ChecklistIndex": -1,
                        "FirstTime":true,
                        "ItemID":0]
        NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
    }
    func handleFristTime() {
        let userDefault = NSUserDefaults.standardUserDefaults()
        let firstTime = userDefault.boolForKey("FirstTime")
        if firstTime {
            let checklist = Checklist(name: "List")
            lists.append(checklist)
            indexOfSelectedChecklist = 0
            userDefault.setBool(false, forKey: "FirstTime")
        }
    }
    func sortChecklists(){
        lists.sortInPlace({checklist1,checklist2 in return checklist1.name.localizedStandardCompare(checklist2.name) == NSComparisonResult.OrderedAscending})
    }
    class func nextChecklistItemID() -> Int {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let itemID = userDefaults.integerForKey("ItemID")
        userDefaults.setInteger(itemID+1, forKey: "ItemID")
        userDefaults.synchronize()
        return itemID
    }
}